/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package threading_webserver;

import com.sun.org.apache.xalan.internal.lib.ExsltDatetime;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;

/**
 *
 * @author Koen
 */
public class Logger extends Thread {

    private final int BUFFERSIZE = 10;
    private String[] buffer;
    private int index = -1;
    private boolean available = true;

    private File file;
    
    public Logger() {
        buffer = new String[BUFFERSIZE];
        this.start();
    }

    @Override
    public void run() 
    {
        System.out.println("Logger started");
        while (true) 
        {
            try {
                writeBufferToLog();
            } catch (IOException ex) {
                System.out.println(ex.toString());
            }
        }
    }
    
    public synchronized void WriteToLog(String IP, String dateTime, String url, int latency) 
    {
        System.out.println("WriteToLog()");
            
        String logLine = String.format("%s: Client with IP: '%s' requested url: '%s'. request completed after %dms<br>\r\n", dateTime, IP, url, latency);
        
        putStringInBuffer(logLine);
    }
    
    private synchronized void putStringInBuffer(String logLine)
    {
        while(!available || bufferIsFull())
        {
            try {
                System.out.println("--- Buffer not available ---");
                wait();
            } catch (InterruptedException ex) {
                System.out.println("interupted");
            }
        }
        available = false;
        notifyAll();
        index = incrementIndex(index);
        System.out.println(index);
        if (buffer[index] == null || buffer[index].trim().isEmpty()) 
        {
            buffer[index] = logLine;
        }
        available = true;
        notifyAll();
    }
    
    private synchronized void writeBufferToLog() throws IOException
    {
        while(!available || bufferIsEmpty())
        {
            try {
                System.out.println("--- Buffer not available ---");
                wait();
            } catch (InterruptedException ex) {
                System.out.println("interupted");
            }
        }
        available = false;
        notifyAll();
        file = new File(String.format("%s\\%s", Settings.webRoot, "log.txt"));
        BufferedWriter writer = new BufferedWriter(new FileWriter(file, true));

        int i = incrementIndex(index);
        do {                        
            if(buffer[i] != null)
            {
                if(!buffer[i].trim().isEmpty())
                {
                    String logLine = buffer[i];
                    writer.write(logLine, 0, logLine.length());

                    buffer[i] = null;
                }
            }
            i = incrementIndex(i);
            
        } while (i != incrementIndex(index));
        file = null;
        writer.close();
        available = true;
        notifyAll();
    }
    
    private synchronized boolean bufferIsFull()
    {
        for (String string : buffer) 
        {
            if(string == null || string.trim().isEmpty())
                return false;
        }
        return true;
    }
    
    private synchronized boolean bufferIsEmpty()
    {
        for (String string : buffer) 
        {
            if(string != null && !string.trim().isEmpty())
                return false;
        }
        return true;
    }

    private int incrementIndex(int i) 
    {
        if(i == (BUFFERSIZE - 1))
            i = 0;
        else
            i++;
        return i;
    }
}
